<template>
    <div>
        <el-dialog
            title="修改产品"
            :visible.sync="dialogVisible"
            width="880px"
        >
            <el-form ref="form" :model="form" label-width="120px" size="small">
                <el-form-item label="农场名称:" prop="farmId">
                    <el-select v-model="form.farmId" placeholder="请选择" style="width: 100%;">
                        <el-option

                            v-for="item in farmNameList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="地区名称:" prop="areaId">
                    <el-select v-model="form.areaId" placeholder="请选择" style="width: 100%;">
                        <el-option
                            v-for="item in farmNameRegion"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="农作物名称:" prop="cropsId">
                    <el-select v-model="form.cropsId" placeholder="请选择" style="width: 100%;">
                        <el-option
                            v-for="item in cropsList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品名称:" prop="name">
                    <el-input :autofocus="true" v-model="form.name" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="产品图片:" prop="image">
                    <el-upload
                        class="upload-demo"
                        :action="action"
                        :headers="{ Authorization: 'Bearer ' + token }"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :file-list="fileList"
                        :before-upload="beforeUpload"
                        :limit=1
                        :on-success="handleSuccess"
                        :on-exceed="handleExceed"
                        list-type="picture">
                        <el-button size="small" type="primary">点击修改</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        <img v-if="imageUrl" :src="imageUrl" class="avatar"
                             style="width: 120px;height: 120px;margin-left: 20px;">
                    </el-upload>
                </el-form-item>
                <el-form-item label="产品价格:" prop="price">
                    <el-input :autofocus="true" v-model="form.price" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="是否热销:" prop="isHot">
                    <el-switch
                        v-model="form.isHot"
                        active-color="#409eff"
                        inactive-color="#dcdfe6">
                    </el-switch>
                </el-form-item>
                <el-form-item label="排序:" prop="listOrder" :rules="rules.listOrder">
                    <el-input :autofocus="true" v-model="form.listOrder" placeholder="请输入排序"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel" size="small">取 消</el-button>
                <el-button type="primary" @click="onSubmit" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {mapState} from "vuex";
import {upDateProduct} from "@/index/api/index/adoption/adoptionManage/adoptionPackage/productManage/index"
import {farmList} from "@/index/api/index/adoption/farm/farm"
import {farmAreaList} from "@/index/api/index/adoption/farmArea/farmArea"
import {cropsList} from "@/index/api/index/adoption/adoptionManage/adoptionPackage/cropsManage/index"

export default {
    mounted() {
        this.getFarmName()
        this.getFarmRegion()
        this.getCropsList()
    },
    data() {
        return {
            dialogVisible: false,
            form: {
                farmId: "",
                areaId: "",
                cropsId: "",
                name: "",
                image: "",
                imgUrl: "",
                price: "",
                isHot: "",
                listOrder: "",
            },
            farmNameList: [],
            farmNameRegion: [],
            cropsList: [],
            fileList: [],
            rules: {
                listOrder: [
                    {
                        validator: (rule, value, callback) => {
                            if (/^[1-9]\d*$/.test(value) === false) {
                                callback(new Error("请输入正整数"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ]
            },
            imageUrl: ""
        }
    },
    computed: {
        ...mapState(["token", "action", "baseUrl"]),
    },
    methods: {
        bindBody(e) {
            this.form.content = e
        },
        cancel() {
            this.dialogVisible = false;
            this.$refs["form"].resetFields();
            this.fileList = []
        },
        showDialog(e, row) {
            this.form = row
            this.imageUrl = this.baseUrl + row.image
            this.form.isHot = row.isHot == 1 ? true : false
            console.log(row)
            const matchedItem = this.farmNameList.find(item => item.name === row.farmId);
            if(matchedItem){
                this.form.farmId = matchedItem.id
            }
            const matchedItem1 = this.farmNameRegion.find(item => item.name === row.areaId);
            if(matchedItem1){
                this.form.areaId = matchedItem1.id
            }
            const matchedItem2 = this.cropsList.find(item => item.name === row.cropsId);
            if(matchedItem2){
                this.form.cropsId = matchedItem2.id
            }

            this.dialogVisible = !this.dialogVisible
        },
        onSubmit() {
            this.form.isHot = true ? 1 : 0
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    upDateProduct(this.form, this.form.id).then(res => {
                        if (res.code == 200) {
                            this.dialogVisible = false;
                            this.$message({
                                message: res.message,
                                type: "success",
                            });
                            this.$parent.getFarmList();
                            this.$refs["form"].resetFields();
                            this.fileList = []
                        } else {
                            this.$message({
                                message: res.message,
                                type: "error",
                            });
                        }
                    })
                } else {
                    this.$message.warning('请输入正确的信息')
                }
            })
        },
        getFarmName() {
            farmList(this.form).then(res => {
                if (res.code == 200) {
                    this.farmNameList = res.data.items
                }
            })
        },
        getFarmRegion() {
            farmAreaList(this.form).then(res => {
                if (res.code == 200) {
                    this.farmNameRegion = res.data.items
                }
            })
        },
        getCropsList() {
            cropsList(this.form).then(res => {
                if (res.code == 200) {
                    this.cropsList = res.data.items
                }
            })
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleExceed() {
            this.$message.warning('最多只能上传一个文件!');
        },
        handleSuccess(file, fileList) {
            if (file.code == 200) {
                this.$message.success(file.message)
                this.form.image = file.data.filePath
                this.imageUrl = ''
            }
        },
        beforeUpload(file) {
            const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt500K = file.size / 1024 < 500;

            if (!isJPGorPNG) {
                this.$message.error('只能上传 JPG 或 PNG 格式的图片文件!');
            }
            if (!isLt500K) {
                this.$message.error('上传的图片文件不能超过 500KB!');
            }
            return isJPGorPNG && isLt500K;
        },
    }
}
</script>

<style lang="less" scoped>

.flex-container {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-top: 10px;
}
</style>
